package com.ruoyi.system.service.impl;
import java.util.Date;
import java.util.HashMap;

import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.core.redis.RedisKey;
import com.ruoyi.common.enums.CrmDataStatus;
import com.ruoyi.common.enums.CrmIsDeleteType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.dto.LitterBsAreaDTO;
import com.ruoyi.system.domain.dto.LitterBsCityDTO;
import com.ruoyi.system.domain.dto.LitterBsStreetDTO;
import com.ruoyi.system.domain.dto.SysAddressDTO;
import com.ruoyi.system.domain.sysutil.LongitudeLatitude;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 【请填写功能名称】Service业务层处理
 * 
 * @author ruoyi
 * @date 2020-10-12
 */
@Service
public class CrmUserServiceImpl implements ICrmUserService
{
    @Autowired
    private CrmUserMapper crmCustomerMapper;

    @Autowired
    private CrmJobMapper crmJobMapper;

    @Autowired
    private CJobCustomerMapper cJobCustomerMapper;

    @Autowired
    private ICrmJobService crmJobServiceImpl;

    @Autowired
    private BsAreaMapper bsAreaMapper;

    @Autowired
    private BsCityMapper bsCityMapper;
    @Autowired
    private BsStreetMapper bsStreetMapper;

    @Autowired
    private BsProvinceMapper bsProvinceMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IBsAreaService bsAreaServiceImpl;


    @Autowired
    private ICIndustryService cIndustryServiceImpl;

    @Autowired
    private  CCustomerLabelMapper cCustomerLabelMapper;

    @Autowired
    private  CrmLabelMapper crmLabelMapper;


    @Autowired
    private ICrmGroupService crmGroupServiceImpl;
    /**
     * 查询
     * 
     * @param id ID
     * @return
     */
    @Override
    public CrmUser selectCrmCustomerById(Long id)
    {
        CrmUser crmCustomer = crmCustomerMapper.selectCrmUserById(id);
        CCustomerLabel param=new CCustomerLabel();
        //param.setLabelName(null);
        param.setIsDelete(CrmIsDeleteType.OK.getCode());
        List<CIndustry> cIndustries = cIndustryServiceImpl.selectCIndustryList(null);
        Map<String, CIndustry> collect = cIndustries.stream().collect(Collectors.toMap(CIndustry::getIndustryCode, a -> a, (k1, k2) -> k1));
        if(crmCustomer!=null && crmCustomer.getCusIndustry() != null && crmCustomer.getCusIndustry().contains(",")){
            String[] split = crmCustomer.getCusIndustry().split(",");
            StringBuffer sbf=new StringBuffer("");
            for(Integer i =0;i<split.length;i++){
                CIndustry cIndustry = collect.get(split[i]);
                if(cIndustry != null){
                    sbf.append(cIndustry.getcIndName()).append(",");
                }
            }
            String s = sbf.toString();
            s = s.substring(0,s.length() - 1);
            crmCustomer.setCusIndustryName(s);
        }

        CCustomerLabel cCustomerLabel=new CCustomerLabel();
        cCustomerLabel.setCusId(id);
        List<CCustomerLabel> crmLabels = cCustomerLabelMapper.selectCCustomerLabelList(cCustomerLabel);
        crmCustomer.setCCustomerLabelList(crmLabels);
        CrmGroup paramG= crmGroupServiceImpl.selectCrmGroupById(crmCustomer.getCusGroupId());
        crmCustomer.setCrmGroup(paramG);
        return crmCustomer;
    }

    /**
     * 查询【请填写功能名称】列表
     * 
     * @param crmCustomer 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<CrmUser> selectCrmCustomerList(CrmUser crmCustomer)
    {
        crmCustomer.setIsDelete(CrmIsDeleteType.OK.getCode());
        crmCustomer.setStatus(CrmDataStatus.OK.getCode());
        List<CrmUser> crmCustomers=  crmCustomerMapper.selectCrmUserList(crmCustomer);
        return crmCustomers;
    }

    /**
     * 查询所有客户 并按照城市进行分组
     *
     */
    @Override
    public LitterBsCityDTO selectCrmCustomerListByMap(CrmUser crmCustomer, Integer type)
    {
        crmCustomer.setIsDelete(CrmIsDeleteType.OK.getCode());
        crmCustomer.setStatus(CrmDataStatus.OK.getCode());
        List<CrmUser> crmCustomers =  crmCustomerMapper.selectCrmUserList(crmCustomer);
        LitterBsCityDTO litterBsCityDTO=new LitterBsCityDTO();
        BsArea bsArea=new BsArea();
        List<BsArea> areaList=bsAreaMapper.selectBsAreaList(bsArea);
        BsCity bsCity=new BsCity();
        bsCity.setCityCode(crmCustomer.getCusCityCode());
        List<BsCity> cityList=bsCityMapper.selectBsCityList(bsCity);
        BsCity city=new BsCity();
        if(cityList!=null && cityList.size()>0){
            city=cityList.get(0);
        }
        int cityNum=0;
        List<LitterBsAreaDTO> litterBsAreaDTOList=new ArrayList<>();
        if(type!=null && type==1){//层级到街道
            BsStreet bsStreet=new BsStreet();
            List<BsStreet> streetList=bsStreetMapper.selectBsStreetList(bsStreet);
            //做转换
            List<LitterBsStreetDTO> litterBsStreetDTOList=new ArrayList<LitterBsStreetDTO>();
            Map<String, List<CrmUser>> collect = crmCustomers.stream().collect(Collectors.groupingBy(CrmUser::getCusStreetCode));
            for(String key:collect.keySet()){
                LitterBsStreetDTO litterBsStreetDTO=new LitterBsStreetDTO();
                for(BsStreet bsStreet1:streetList){
                    if(bsStreet1.getStreetCode().equals(key)){
                        bsStreet=bsStreet1;
                        break;
                    }
                }
                litterBsStreetDTO.setStreetCode(key);
                litterBsStreetDTO.setStreetName(bsStreet.getStreetName());
                litterBsStreetDTO.setAreaCode(bsStreet.getAreaCode());
                litterBsStreetDTO.setLat(bsStreet.getLat());
                litterBsStreetDTO.setLng(bsStreet.getLng());
                List<CrmUser> crmCustomerList=collect.get(key);
                litterBsStreetDTO.setCrmCustomerList(crmCustomerList);
                litterBsStreetDTO.setCustomerNum(collect.get(key).size());
                litterBsStreetDTOList.add(litterBsStreetDTO);
            }
            Map<String, List<LitterBsStreetDTO>> collect1 = litterBsStreetDTOList.stream().collect(Collectors.groupingBy(LitterBsStreetDTO::getAreaCode));
            for(String key:collect1.keySet()){
                LitterBsAreaDTO litterBsAreaDTO=new LitterBsAreaDTO();
                litterBsAreaDTO.setAreaCode(key);
                for(BsArea bsArea1:areaList){
                    if(bsArea1.getAreaCode().equals(key)){
                        bsArea=bsArea1;
                        break;
                    }
                }
                litterBsAreaDTO.setAreaName(bsArea.getAreaName());
                litterBsAreaDTO.setLat(bsArea.getLat());
                litterBsAreaDTO.setLng(bsArea.getLng());
                litterBsAreaDTO.setCityCode(bsArea.getCityCode());
                List<LitterBsStreetDTO> litterBsStreetDTOList1=collect1.get(key);
                litterBsAreaDTO.setLitterBsStreetDTOList(litterBsStreetDTOList1);
                int areaNum=0;
                for(LitterBsStreetDTO litterBsStreetDTO:litterBsStreetDTOList1){
                    areaNum+=litterBsStreetDTO.getCustomerNum();
                }
                litterBsAreaDTO.setCustomerNum(areaNum);
                litterBsAreaDTOList.add(litterBsAreaDTO);
            }
            for(LitterBsAreaDTO litterBsAreaDTO:litterBsAreaDTOList){
                cityNum+=litterBsAreaDTO.getCustomerNum();
            }
            litterBsCityDTO.setLat(city.getLat());
            litterBsCityDTO.setLng(city.getLng());
            litterBsCityDTO.setCustomerNum(cityNum);
            litterBsCityDTO.setCityName(city.getCityName());
            litterBsCityDTO.setCityCode(city.getCityCode());
            litterBsCityDTO.setLitterBsAreaDTOList(litterBsAreaDTOList);
        } else {//层级到区县
            Map<String, List<CrmUser>> collect = crmCustomers.stream().collect(Collectors.groupingBy(CrmUser::getCusAreaCode));
            for(String key:collect.keySet()){
                LitterBsAreaDTO litterBsAreaDTO=new LitterBsAreaDTO();
                litterBsAreaDTO.setAreaCode(key);
                for(BsArea bsArea1:areaList){
                    if(bsArea1.getAreaCode().equals(key)){
                        bsArea=bsArea1;
                        break;
                    }
                }
                litterBsAreaDTO.setAreaName(bsArea.getAreaName());
                litterBsAreaDTO.setLat(bsArea.getLat());
                litterBsAreaDTO.setLng(bsArea.getLng());
                List<CrmUser> crmCustomerList=collect.get(key);
                litterBsAreaDTO.setCrmCustomerList(crmCustomerList);
                litterBsAreaDTO.setCustomerNum(collect.get(key).size());
                litterBsAreaDTOList.add(litterBsAreaDTO);
            }
            for(LitterBsAreaDTO litterBsAreaDTO:litterBsAreaDTOList){
                cityNum+=litterBsAreaDTO.getCustomerNum();
            }

        }
        litterBsCityDTO.setLat(city.getLat());
        litterBsCityDTO.setLng(city.getLng());
        litterBsCityDTO.setCustomerNum(cityNum);
        litterBsCityDTO.setCityName(city.getCityName());
        litterBsCityDTO.setCityCode(city.getCityCode());
        litterBsCityDTO.setLitterBsAreaDTOList(litterBsAreaDTOList);
        return litterBsCityDTO;
    }

    @Override
    public List<CrmUser> selectCrmCustomerListNew(CrmUser crmCustomer, String title) {
        crmCustomer.setIsDelete(CrmIsDeleteType.OK.getCode());
        crmCustomer.setStatus(CrmDataStatus.OK.getCode());
        List<CrmUser> crmCustomers = null;

        if(StringUtils.isNotEmpty(title)){
            crmCustomer.setCusName(title);
            crmCustomers = crmCustomerMapper.selectCrmUserListNew(crmCustomer);
        }else{
            crmCustomers= redisCache.getCacheList(RedisKey.GEO_SYSTEM_CRMUSER+crmCustomer.getCreateUser());
            if(crmCustomers.isEmpty()){
                crmCustomers= crmCustomerMapper.selectCrmUserListNew(crmCustomer);
            }
        }
        //行业须放入缓存
        List<CIndustry> cIndustries = cIndustryServiceImpl.selectCIndustryList(null);
        Map<String, CIndustry> collect = cIndustries.stream().collect(Collectors.toMap(CIndustry::getIndustryCode, a -> a, (k1, k2) -> k1));
        for (CrmUser tmp : crmCustomers
             ) {
            if(tmp.getCusIndustry() != null && tmp.getCusIndustry().contains(",")){
                String[] split = tmp.getCusIndustry().split(",");
                StringBuffer sbf=new StringBuffer("");
                for(Integer i =0;i<split.length;i++){
                    if(StringUtils.isEmpty(split[i])){
                        continue;
                    }
                    CIndustry cIndustry = collect.get(split[i]);
                    if(cIndustry != null){
                        sbf.append(cIndustry.getcIndName()).append(",");
                    }
                }
                String s = sbf.toString();
                s = s.substring(0,s.length() - 1);
                tmp.setCusIndustryName(s);
            }
        }
        CrmGroup paramG=new CrmGroup();
        paramG.setCreateUser(crmCustomer.getCreateUser());
        List<CrmGroup> crmGroups = crmGroupServiceImpl.selectCrmGroupList(paramG);
        Map<Long, CrmGroup> crmGroupsMap = crmGroups.stream().collect(Collectors.toMap(CrmGroup::getId, a -> a, (k1, k2) -> k1));
        for (CrmUser tmp : crmCustomers
             ) {
            if(tmp.getCusGroupId() != null &&crmGroupsMap.get(tmp.getCusGroupId()) != null){
                CrmGroup crmGroup = crmGroupsMap.get(tmp.getCusGroupId());
                tmp.setCrmGroup(crmGroup);
            }
        }
        return crmCustomers;
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param crmCustomer 【请填写功能名称】
     * @return 结果
     */
    @Override
    @Transactional
    public int insertCrmCustomer(CrmUser crmCustomer, Long userId)
    {
        crmCustomer.setCreateTime(new Date());
        crmCustomer.setUpdateTime(new Date());
        crmCustomer.setCreateUser(userId);
        crmCustomer.setUpdateUser(userId);
        crmCustomer.setStatus(CrmDataStatus.OK.getCode());
        crmCustomer.setIsDelete(CrmIsDeleteType.OK.getCode());
        if(null!=crmCustomer.getCusLalg() && !"".equals(crmCustomer.getCusLalg())) {
            //根据坐标获取  省市区码
            BsArea areaByLgla = bsAreaServiceImpl.getAreaByLgla(crmCustomer.getCusLalg());
            if (areaByLgla != null) {
                SysAddressDTO addressCodeByArea = bsAreaServiceImpl.getAddressCodeByArea(areaByLgla);
                if (addressCodeByArea != null) {
                    if(addressCodeByArea.getBsProvince()!=null)
                    crmCustomer.setCusProvinceCode( addressCodeByArea.getBsProvince().getProvinceCode());
                    if(addressCodeByArea.getBsCity()!=null)
                    crmCustomer.setCusCityCode(addressCodeByArea.getBsCity().getCityCode());
                    if(addressCodeByArea.getBsArea()!=null)
                    crmCustomer.setCusAreaCode(addressCodeByArea.getBsArea().getAreaCode());
                }
            }
        }
        int i = crmCustomerMapper.insertCrmUser(crmCustomer);
        if(null!=crmCustomer.getCusLalg() && !"".equals(crmCustomer.getCusLalg()) && !"undefined".equals(crmCustomer.getCusLalg())) {
            System.out.println("crmCustomer.getCusLalg()==========="+crmCustomer.getCusLalg());
            LongitudeLatitude coordinateByLgla = LongitudeLatitude.getCoordinateByLgla(crmCustomer.getCusLalg());
            redisCache.redisGeoAdd(RedisKey.GEO_CUSTOMER + userId, coordinateByLgla.getLongitude(), coordinateByLgla.getLatitude(), crmCustomer.getId() + "");
        }
        // 添加客户时添加客户标签
        if(StringUtils.isNotEmpty(crmCustomer.getCusLabel())){
            saveCusLabel(crmCustomer);
        }
        return i;
    }
    public int batchInsertCrmCustomer(List<CrmUser> crmCustomerList){
        //需要增加一个异步的缓存处理功能
       return  crmCustomerMapper.batchInsertCrmUser(crmCustomerList);
    }


    /**
     * 修改【请填写功能名称】
     * 
     * @param crmCustomer 【请填写功能名称】
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateCrmCustomer(CrmUser crmCustomer)
    {
        Long id = crmCustomer.getId();
        if(id == null){
            return 0;
        }
         //用户坐标发生改变   移除原始坐标数据
        CrmUser origCus = crmCustomerMapper.selectCrmUserById(id);
        if(origCus==null || origCus.getId()==0){
            return 0;
        }

        if(StringUtils.isNotEmpty(crmCustomer.getCusLalg()) && ( origCus.getCusLalg()==null || !origCus.getCusLalg().equals(crmCustomer.getCusLalg()))){
            redisCache.deleteObject(RedisKey.GEO_CUSTOMER+crmCustomer.getCreateUser());

        //根据坐标获取  省市区码
        BsArea areaByLgla = bsAreaServiceImpl.getAreaByLgla(crmCustomer.getCusLalg());
        System.out.println("areaByLgla=="+areaByLgla.getAreaCode()+">"+areaByLgla.getCityCode());
        if(areaByLgla!=null){
            SysAddressDTO addressCodeByArea = bsAreaServiceImpl.getAddressCodeByArea(areaByLgla);
            if(addressCodeByArea!=null) {
                crmCustomer.setCusProvinceCode(addressCodeByArea.getBsProvince()!=null?addressCodeByArea.getBsProvince().getProvinceCode():"");
                crmCustomer.setCusCityCode(addressCodeByArea.getBsCity()!=null?addressCodeByArea.getBsCity().getCityCode():"");
                crmCustomer.setCusAreaCode(addressCodeByArea.getBsArea()!=null?addressCodeByArea.getBsArea().getAreaCode():"");
            }
        }
        }
        //编辑客户标签  中间表
        updateCusLabel(crmCustomer);
        return crmCustomerMapper.updateCrmUser(crmCustomer);
    }

    /**
     * 批量删除【请填写功能名称】
     * 
     * @param ids 需要删除的【请填写功能名称】ID
     * @return 结果
     */
    @Override
    public int deleteCrmCustomerByIds(Long[] ids)
    {
        return crmCustomerMapper.deleteCrmUserByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     * 
     * @param id 【请填写功能名称】ID
     * @return 结果
     */
    @Override
    public int deleteCrmCustomerById(Long id)
    {
        return crmCustomerMapper.deleteCrmUserById(id);
    }

    /**
     * 最近联系人
     * @return
     */
    @Override
    public List<CrmUser> recentlyLinkedCustomer(Long userId) {
        CrmJob crmJob=new CrmJob();
        crmJob.setCreateUser(userId);
        crmJob.setStatus(CrmDataStatus.OK.getCode());
        crmJob.setIsDelete(CrmDataStatus.OK.getCode());
        //用户所有任务
        List<CrmJob> crmJobs = crmJobMapper.selectCrmJobList(crmJob);
        //根据用户id 查询最近一个月的  任务
        List<Long> jobIdsMonth = new ArrayList<>();
        for (CrmJob CrmJob : crmJobs
             ) {
            jobIdsMonth.add(CrmJob.getId());
        }
        //根据任务查询所有客户
        List<CJobCustomer> customerByIds = cJobCustomerMapper.getCustomerByIds(jobIdsMonth);
        //统计客户出现次数  倒叙排列
        Map<Long,Integer> cusIdMap=new HashMap<>();
        for (CJobCustomer cJobCustomerTmp :customerByIds
             ) {
            if(cusIdMap.get(cJobCustomerTmp.getCusId()) != null){
                int i = cusIdMap.get(cJobCustomerTmp.getCusId()).intValue();
                i=i+1;
                cusIdMap.put(cJobCustomerTmp.getCusId(),i);
            }
            if(cusIdMap.get(cJobCustomerTmp.getCusId()) == null){
                cusIdMap.put(cJobCustomerTmp.getCusId(),0);
            }
        }
        List<Map.Entry<Long, Integer>> list = new ArrayList<>(cusIdMap.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<Long, Integer>>()
        {
            @Override
            public int compare(Map.Entry<Long, Integer> o1, Map.Entry<Long, Integer> o2)
            {
                //按照value值，从大到小排序
                return o2.getValue() - o1.getValue();
            }
        });
        List<Long> resCusIds=new ArrayList<>();
        for (Map.Entry<Long, Integer> a :list
             ) {
            resCusIds.add(a.getKey());
        }
        CrmUser paramCus=new CrmUser();
        paramCus.setIsDelete(CrmIsDeleteType.OK.getCode());
        paramCus.setStatus(CrmDataStatus.OK.getCode());
        paramCus.setCreateUser(userId);
        List<CrmUser> crmCustomers = crmCustomerMapper.selectCrmUserByIds(resCusIds,paramCus);
        Map<Long, CrmUser> crmCustomerMapSort = crmCustomers.stream().collect(Collectors.toMap(CrmUser::getId, crmCustomer -> crmCustomer, (k1, k2) -> k1));
        List<CrmUser> crmCustomersResult = new ArrayList<>();
        for (Long cusId :resCusIds
             ) {
            if(crmCustomerMapSort.get(cusId) !=null){
                crmCustomersResult.add(crmCustomerMapSort.get(cusId));
            }

        }
        return crmCustomersResult;
    }


    @Override
    public Integer deleteCustomerAndJob(Long crmCustomerId, Long userId) {
        //查询当前用户是否可以删除
        CrmUser crmCustomer= new CrmUser();
        crmCustomer.setId(crmCustomerId);
        crmCustomer.setStatus(CrmDataStatus.OK.getCode());
        crmCustomer.setCreateUser(userId);
        crmCustomer.setIsDelete(CrmIsDeleteType.DELETE.getCode());
        int i = crmCustomerMapper.updateCrmUser(crmCustomer);
        return i;
    }

    @Override
    public List<CrmUser> getNearCrmCustomer(Long id, Integer distance, Integer count) {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        CrmUser crmCustomer = crmCustomerMapper.selectCrmUserById(id);
        //redis 填充 坐标
        if(!redisCache.isHasKey(RedisKey.GEO_CUSTOMER+userId)){
            CrmUser param=new CrmUser();
            param.setStatus(CrmDataStatus.OK.getCode());
            param.setIsDelete(CrmIsDeleteType.OK.getCode());
            param.setCreateUser(userId);
            List<CrmUser> crmCustomers = crmCustomerMapper.selectCrmUserList(param);
            for ( CrmUser tmp :crmCustomers
                 ) {
                if(StringUtils.isNotEmpty(tmp.getCusLalg())){
                    LongitudeLatitude coordinateByLgla = LongitudeLatitude.getCoordinateByLgla(tmp.getCusLalg());
                    redisCache.redisGeoAdd(RedisKey.GEO_CUSTOMER+userId,coordinateByLgla.getLongitude(),coordinateByLgla.getLatitude(),tmp.getId()+"");
                }
            }
        }
        if(distance == null){
            distance= 0;
        }
        if(count == null){
            count =0;
        }
        //获取附近的客户
        List<Long> cusIds=new ArrayList<>();
        GeoResults<RedisGeoCommands.GeoLocation<String>> geoResults = redisCache.geoNearByPlace(RedisKey.GEO_CUSTOMER+userId, crmCustomer.getId() + "", distance, count);
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> content = geoResults.getContent();
        for (GeoResult<RedisGeoCommands.GeoLocation<String>> geo : geoResults
             ) {
            //获取附近的客户id
            Long  cusID = StringUtils.isNotEmpty(geo.getContent().getName()) ? Long.parseLong(geo.getContent().getName()) : 0l;
            cusIds.add(cusID);
        }
        List<CrmUser> crmCustomers = crmCustomerMapper.selectCrmUserByIds(cusIds, null);
        return crmCustomers;
    }


    @Override
    public List<CrmUser> getNearCrmCustomerByLgLa(Long userId,String lgla,Integer distance) {
        LongitudeLatitude coordinateByLgla1 = LongitudeLatitude.getCoordinateByLgla(lgla);
        //redis 填充 坐标
        if(!redisCache.isHasKey(RedisKey.GEO_CUSTOMER+userId)){
            CrmUser param=new CrmUser();
            param.setStatus(CrmDataStatus.OK.getCode());
            param.setIsDelete(CrmIsDeleteType.OK.getCode());
            param.setCreateUser(userId);
            List<CrmUser> crmCustomers = crmCustomerMapper.selectCrmUserList(param);
            for ( CrmUser tmp :crmCustomers
            ) {
                if(StringUtils.isNotEmpty(tmp.getCusLalg())){
                    LongitudeLatitude coordinateByLgla = LongitudeLatitude.getCoordinateByLgla(tmp.getCusLalg());
                    if(coordinateByLgla != null && coordinateByLgla.getLongitude() != null && coordinateByLgla.getLatitude() !=null){
                        redisCache.redisGeoAdd(RedisKey.GEO_CUSTOMER+userId,coordinateByLgla.getLongitude(),coordinateByLgla.getLatitude(),tmp.getId()+"");
                    }
                }
            }
        }
       Integer count =9999;
        //获取附近的客户
        List<Long> cusIds=new ArrayList<>();
        GeoResults<RedisGeoCommands.GeoLocation<String>> geoResults = redisCache.redisNearByXY(RedisKey.GEO_CUSTOMER+userId, coordinateByLgla1.getLongitude(),coordinateByLgla1.getLatitude(), distance, count);
        //List<GeoResult<RedisGeoCommands.GeoLocation<String>>> content = geoResults.getContent();
        for (GeoResult<RedisGeoCommands.GeoLocation<String>> geo : geoResults
        ) {
            //获取附近的客户id
            Long  cusID = StringUtils.isNotEmpty(geo.getContent().getName()) ? Long.parseLong(geo.getContent().getName()) : 0l;
            cusIds.add(cusID);
        }
        //当前用户的客户
        CrmUser param =new CrmUser();
        param.setCreateUser(userId);
        param.setIsDelete(CrmIsDeleteType.OK.getCode());
        param.setStatus(CrmDataStatus.OK.getCode());
         List<CrmUser> crmCustomers = crmCustomerMapper.selectCrmUserByIds(cusIds, param);
        return crmCustomers;
    }

    @Override
    public List<CrmUser> selectCrmCustomerListByIds(List<Long> ids){
        return crmCustomerMapper.selectCrmUserByIds(ids, null);
    }

    /**
     * 客户标签 中间表写入
     * @param
     */
    public void saveCusLabel(CrmUser crmUser){
        //先删除对应标签
        cCustomerLabelMapper.deleteCCustomerLabelByCusId(crmUser.getId());
        String[] split = crmUser.getCusLabel().split(",");
        List<String> labelList = Arrays.asList(split);
        //List<Long> labelListLong = labelList.stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        List<CCustomerLabel > cCustomerLabelList=new ArrayList<>();
        for (String label : labelList
             ) {
            CCustomerLabel cCustomerLabel=new CCustomerLabel();
            cCustomerLabel.setCreateTime(new Date());
            cCustomerLabel.setUpdateTime(new Date());
            cCustomerLabel.setIsDelete(CrmIsDeleteType.OK.getCode());
            cCustomerLabel.setCusId(crmUser.getId());
            cCustomerLabel.setCreateUser(crmUser.getCreateUser());

            cCustomerLabel.setLabelName(label);
           // cCustomerLabel.setLabelId(label);
            cCustomerLabel.setCreateTime(DateUtils.getNowDate());
            cCustomerLabelList.add(cCustomerLabel);
            //cCustomerLabelMapper.insertCCustomerLabel(cCustomerLabel);
        }
        //优化为批量插入接口
        cCustomerLabelMapper.batchInsertCCustomerLabel(cCustomerLabelList);
    }

    /**
     * 修改客户标签中间表
     * @param crmCustomer
     */
    public void updateCusLabel(CrmUser crmCustomer){
        String cusLabel = crmCustomer.getCusLabel();
        cCustomerLabelMapper.deleteCCustomerLabelByCusId(crmCustomer.getId());
        if(StringUtils.isNotEmpty(cusLabel)){
            String[] split = cusLabel.split(",");
             List<String> labelList = Arrays.asList(split);
             //List<Long> labelListLong = labelList.stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
            List<CCustomerLabel > cCustomerLabelList=new ArrayList<>();

            for (String lab :labelList
            ) {
                CCustomerLabel insert=new CCustomerLabel();
                insert.setCusId(crmCustomer.getId());
                insert.setLabelName(lab);
                insert.setCreateUser(crmCustomer.getCreateUser());
                //insert.setLabelId(lab);
                insert.setIsDelete(CrmIsDeleteType.OK.getCode());
                insert.setCreateTime(new Date());
                insert.setUpdateTime(new Date());
                cCustomerLabelList.add(insert);
               // cCustomerLabelMapper.insertCCustomerLabel(insert);
            }
            cCustomerLabelMapper.batchInsertCCustomerLabel(cCustomerLabelList);

        }
    }

    /**
     * 查看最近一段时间内跟进的客户列表
     * @param startTime
     * @param endTime
     * @param createUser
     * @return
     */
    public List<CrmUser> selectCrmUserListByTime(Date startTime, Date endTime, Long createUser){
        return crmCustomerMapper.selectCrmUserListByTime(startTime,endTime,createUser);
    }

    /**
     * 查看最近几天内未跟进的客户情况
     * @param startTime
     * @param endTime
     * @param createUser
     * @return
     */
    public List<CrmUser> selectCrmUserListByNoTime(Date startTime, Date endTime, Long createUser){
        return crmCustomerMapper.selectCrmUserListByNoTime(startTime,endTime,createUser);
    }


    /**
     * 查看未来几天内过生日的人
     * @param day 天数

     * @param createUser
     * @return
     */
    public List<CrmUser> selectCrmUserListByBirthDayByDay(int day, Long createUser){
        return crmCustomerMapper.selectCrmUserListByBirthDayByDay(day,createUser);
    }
    /**
     *查看周期内过生日的人
     * @param type type=1代表今天 2代表本周 3代表下周4代表本月5代表下月
     * @param createUser
     * @return
     */
    public List<CrmUser> selectCrmUserListByBirthDay(Integer type, Long createUser){
      if(type==1){
          return crmCustomerMapper.selectCrmUserListByCurDayBirthDayTime(createUser);
      }else if(type==2){
          return crmCustomerMapper.selectCrmUserListByCurWeekBirthDayTime(createUser);
      }else if(type==3){
          return crmCustomerMapper.selectCrmUserListByNextWeekBirthDayTime(createUser);
      }else if(type==4){
            return crmCustomerMapper.selectCrmUserListByCurMonthBirthDayTime(createUser);
      }else if(type==5){
            return crmCustomerMapper.selectCrmUserListByNextMonthBirthDayTime(createUser);
      }else{
            return crmCustomerMapper.selectCrmUserListByCurDayBirthDayTime(createUser);
        }
    }

}
